package com.example.emos.wx.core.common.ex;

import com.example.emos.wx.core.exception.EmosException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2023/8/2
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {
    /**
     * 全局异常处理方法
     *
     * @param e 捕获的异常
     * @return 精简后的异常内容
     */
    @ResponseBody
    //规定响应的状态码
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    //捕获异常
    @ExceptionHandler(Exception.class)
    public String validExceptionHandler(Exception e) {
        log.error("执行异常", e);
        //后端验证失败抛出异常MethodArgumentNotValidException
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            //获取具体的异常消息
            return exception.getBindingResult().getFieldError().getDefaultMessage();
        }
        //出现EmosException时
        else if (e instanceof EmosException) {
            EmosException exception = (EmosException) e;
            return exception.getMsg();
        }
        //未授权异常
        else if (e instanceof UnauthorizedException) {
            return "无权限操做，请联系管理人员";
        }
        //未知异常
        else {
            return "后端服务器正在更新中,请稍后重试";
        }
    }
}
